<?php

namespace App\Http\Controllers\Api;

use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class RoleController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:admin',['except'=>['index','show']]);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $per_page = $request->get('per_page',10);
        $current_page = $request->get('current_page',1);
        $withPage = $request->get('with_page',false);
        if ($withPage) {
            return Role::query()->forPage($current_page)->paginate($per_page);
        } else {
            return Role::query()->get();
        }

    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $name = $request->name;
        $ids = json_decode($request->ids);
        $role = Role::create(['guard_name'=>'admin','name'=>$name]);
        $permissions = Permission::query()->findMany($ids);
        $role->givePermissionTo($permissions);
        return $role;

    }

    public function show($id)
    {
        $role = Role::query()->find($id);
        $allPermission =  Permission::all()->groupBy('table_name');;
        $permissions =  $role->permissions()->get();
        $role->permissions = $permissions;
        $role->all_permissions = $allPermission;
        return $role;
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $ids = $request->ids;
        $role = Role::query()->find($id);
        $permissions = Permission::query()->findMany(json_decode($ids));
        $role->syncPermissions($permissions);
        return $role;
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $role = Role::query()->find($id);
        $role->delete();
        return ['code'=>200];
    }
}
